import json
import random
import re
from django import http
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, redirect
from django_redis import get_redis_connection

from carts.utils import merge_cookie_redis_cart
from celery_tasks.email.tasks import send_verify_url
from goods.models import SKU
from users.models import User, Address

from django.views import View

from meiduo_mall.utils.my_login_required import MyLoginRequiredMiXinView
from meiduo_mall.utils.emails import generate_verify, decode_token
from meiduo_mall.utils.response_code import RET
from verifications import constants


class RegisterView(View):
    def get(self, request):
        return render(request, 'register.html')

    def post(self, request):
        # 获取参数
        user_name = request.POST.get("user_name")
        pwd = request.POST.get("pwd")
        cpwd = request.POST.get("cpwd")
        phone = request.POST.get("phone")
        msg_code = request.POST.get("msg_code")
        allow = request.POST.get("allow")

        # 校验参数
        # 为空校验
        if not all([user_name, pwd, cpwd, phone, msg_code, allow]):
            return http.HttpResponseForbidden("参数不全")
        # 两次密码校验
        if pwd != cpwd:
            return http.HttpResponseForbidden("两次密码不一致")
        # 手机号格式校验
        if not re.match(r'1[3-9]\d{9}', phone):
            return http.HttpResponseForbidden("手机号格式有误")
        # 短信验证码校验
        redis_conn = get_redis_connection("code")
        redis_msg_code = redis_conn.get("sms_code_%s" % phone)
        if redis_msg_code.decode() != msg_code:
            return http.HttpResponseForbidden("短信验证码输入有误")
        # 协议校验
        if allow != 'on':
            return http.HttpResponseForbidden("必须同意协议")
        # 创建用户保存到数据库中
        user = User.objects.create_user(username=user_name, password=pwd, mobile=phone)
        # 返回响应
        response = redirect("/login")
        return response


class CheckUsernameView(View):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        data = {
            "count": count
        }
        return http.JsonResponse(data)


class CheckMobileView(View):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        data = {
            "count": count
        }
        return http.JsonResponse(data)


class LoginUserView(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        # 获取参数
        username = request.POST.get("username")
        password = request.POST.get("pwd")
        remembered = request.POST.get("remembered")
        # 校验参数
        # 为空校验
        if not all([username, password]):
            return http.HttpResponseForbidden("参数不全")
        # 用户名格式校验
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden("用户名格式有误")
        # 密码格式校验
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden("密码格式有误")
        # 校验用户名和密码的正确性
        user = authenticate(request, username=username, password=password)
        if not user:
            return http.HttpResponseForbidden("账号或密码有误")
        # 状态保持
        login(request, user)

        if remembered == 'on':
            request.session.set_expiry(3600 * 24 * 2)
        else:
            request.session.set_expiry(0)
        # 返回响应
        response = redirect('/')
        response.set_cookie("username", user.username, 3600 * 24 * 2)
        response = merge_cookie_redis_cart(request, user, response)
        return response


class LogoutUserView(View):
    def get(self, request):
        logout(request)
        # 清除cookie
        response = redirect('/')
        response.delete_cookie("username")
        return response


class UserCenterView(MyLoginRequiredMiXinView):
    def get(self, request):
        context = {
            "username": request.user.username,
            "mobile": request.user.mobile,
            "email": request.user.email,
            "email_active": request.user.email_active
        }
        return render(request, 'user_center_info.html', context=context)


class EmailSendView(MyLoginRequiredMiXinView):
    def put(self, request):
        # 获取参数
        dict_data = json.loads(request.body.decode())
        email = dict_data.get("email")
        # 校验参数
        # 为空校验
        if not email:
            return http.HttpResponseForbidden("参数不全")
        # 格式校验
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.HttpResponseForbidden("邮件格式有误")
        # 发送邮件
        verify_url = generate_verify(request.user)
        send_verify_url.delay(verify_url, email)
        # 数据入库
        request.user.email = email
        request.user.save()
        # 返回响应
        return http.JsonResponse({"code": RET.OK, "errmsg": "ok"})


class EmailActiveView(View):
    def get(self, request):
        # 获取token参数
        token = request.GET.get("token")
        # 校验参数
        if not token:
            return http.HttpResponseForbidden("token丢失")
        user = decode_token(token)
        if not user:
            return http.HttpResponseForbidden("token过期")
        # 数据入库
        user.email_active = True
        user.save()
        return redirect('/info')


class AddressView(View):
    def get(self, request):
        # 1,获取用户所有的地址
        addresses = request.user.addresses.filter(is_deleted=False)

        # 2,数据拼接
        addresses_list = []
        for address in addresses:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email,
                "province_id": address.province_id,
                "city_id": address.city_id,
                "district_id": address.district_id
            }
            addresses_list.append(address_dict)

        context = {
            "addresses": addresses_list,
            "default_address_id": request.user.default_address_id
        }

        # 3,返回渲染页面
        return render(request, 'user_center_site.html', context=context)


class AddressCreateView(MyLoginRequiredMiXinView):
    def post(self, request):
        # 1,获取参数
        dict_data = json.loads(request.body.decode())
        title = dict_data.get("title")
        receiver = dict_data.get("receiver")
        province_id = dict_data.get("province_id")
        city_id = dict_data.get("city_id")
        district_id = dict_data.get("district_id")
        place = dict_data.get("place")
        mobile = dict_data.get("mobile")
        tel = dict_data.get("tel")
        email = dict_data.get("email")

        # 2,校验参数
        if not all([title, receiver, province_id, city_id, district_id, place, mobile, email]):
            return http.HttpResponseForbidden("参数不全")

        # 3,数据入库
        dict_data["user"] = request.user
        address = Address.objects.create(**dict_data)

        # 4,返回响应
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email,
            "province_id": address.province_id,
            "city_id": address.city_id,
            "district_id": address.district_id
        }
        return http.JsonResponse({"code": RET.OK, "address": address_dict})


class AddressUpdateView(MyLoginRequiredMiXinView):
    def put(self, request, address_id):
        # 获取参数
        dict_data = json.loads(request.body.decode())
        title = dict_data.get("title")
        receiver = dict_data.get("receiver")
        province_id = dict_data.get("province_id")
        city_id = dict_data.get("city_id")
        district_id = dict_data.get("district_id")
        place = dict_data.get("place")
        mobile = dict_data.get("mobile")
        tel = dict_data.get("tel")
        email = dict_data.get("email")
        # 校验参数
        if not all([title, receiver, province_id, city_id, district_id, place, mobile, tel, email]):
            return http.HttpResponseForbidden("参数不全")
        # 数据入库
        address = Address.objects.get(id=address_id)
        address.title = title
        address.receiver = receiver
        address.province_id = province_id
        address.city_id = city_id
        address.district_id = district_id
        address.place = place
        address.mobile = mobile
        address.tel = tel
        address.email = email
        address.save()
        # 返回响应
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email,
            "province_id": address.province_id,
            "city_id": address.city_id,
            "district_id": address.district_id
        }
        return http.JsonResponse({"code": RET.OK, "address": address_dict})

    def delete(self, request, address_id):
        address = Address.objects.get(id=address_id)
        address.is_deleted = True
        address.save()

        return http.JsonResponse({"code": RET.OK})


class AddressDefaultView(MyLoginRequiredMiXinView):
    def put(self, request, address_id):
        request.user.default_address_id = address_id
        request.user.save()
        return http.JsonResponse({"code": RET.OK})


class AddressTitleView(MyLoginRequiredMiXinView):
    def put(self, request, address_id):
        title = json.loads(request.body.decode()).get("title")
        if not title:
            return http.HttpResponseForbidden("参数不全")
        ret = Address.objects.filter(id=address_id).update(title=title)
        if ret == 0:
            return http.HttpResponseForbidden("修改失败")
        return http.JsonResponse({"code": RET.OK})


class PasswordChangeView(MyLoginRequiredMiXinView):
    def get(self, request):
        return render(request, 'user_center_pass.html')

    def post(self, request):
        # 1,获取参数
        old_pwd = request.POST.get("old_pwd")
        new_pwd = request.POST.get("new_pwd")
        new_cpwd = request.POST.get("new_cpwd")

        # 2,校验参数
        # 2.1为空校验
        if not all([old_pwd, new_pwd, new_cpwd]):
            return http.HttpResponseForbidden("参数不全")

        # 2,2校验密码格式
        if not re.match(r'^[0-9A-Za-z]{8,20}$', old_pwd):
            return http.HttpResponseForbidden("旧密码格式有误")

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_pwd):
            return http.HttpResponseForbidden("旧密码格式有误")

        # 2.3旧密码正确性
        if not request.user.check_password(old_pwd):
            return http.HttpResponseForbidden("旧密码不正确")

        # 2.4两次新密码正确性
        if new_pwd != new_cpwd:
            return http.HttpResponseForbidden("两次新密码不一致")

        # 3,数据入库
        request.user.set_password(new_pwd)
        request.user.save()

        # 4,返回响应,清空session信息
        logout(request)
        response = redirect('/login')
        response.delete_cookie("username")
        return response


class UserBrowserHistoryView(MyLoginRequiredMiXinView):
    def post(self, request):
        # 获取参数
        dict_data = json.loads(request.body.decode())
        sku_id = dict_data.get("sku_id")
        user = request.user
        # 校验参数
        if not sku_id:
            return http.HttpResponseForbidden("参数不全")
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            return http.HttpResponseForbidden("商品不存在")

        # 数据入库
        redis_conn = get_redis_connection("history")
        pipeline = redis_conn.pipeline()
        # 去重
        pipeline.lrem("history_%s" % user.id, 0, sku_id)
        # 存储
        pipeline.lpush("history_%s" % user.id, sku_id)
        # 截取
        pipeline.ltrim("history_%s" % user.id, 0, 4)
        pipeline.execute()
        # 返回响应
        return http.JsonResponse({"code": RET.OK, "errmsg": "ok"})

    def get(self, request):
        # 获取redis中的数据
        redis_conn = get_redis_connection("history")
        sku_ids = redis_conn.lrange("history_%s" % request.user.id, 0, 4)
        # 拼接数据
        sku_list = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_dict = {
                "id": sku.id,
                "default_image_url": sku.default_image_url.url,
                "name": sku.name,
                "price": sku.price,
            }
            sku_list.append(sku_dict)
        return http.JsonResponse({"skus": sku_list})
        pass


class FindPasswordView(View):
    def get(self, request):
        return render(request, 'find_password.html')


class VerifyIdentifyView(View):
    def get(self, request, username):
        dict_name = {"username": username}
        image_code_id = request.GET.get("image_code_id")
        img_code = request.GET.get("text")
        if dict_name not in User.objects.values("username"):
            return http.JsonResponse({"status": '401'})
        redis_conn = get_redis_connection("code")
        redis_image_code = redis_conn.get("image_code_%s" % image_code_id)
        if img_code.lower() != redis_image_code.decode().lower():
            return http.JsonResponse({"status": '4001'})
        mobile = User.objects.filter(username=username).values('mobile')[0]['mobile']
        data = {
            "mobile": mobile,
        }
        return http.JsonResponse(data)


class VerifyIdentifySmscodeView(View):
    def get(self, request):
        mobile = request.GET.get("mobile")
        redis_conn = get_redis_connection("code")
        sms_code = "%06d" % random.randint(0, 999999)
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile, sms_code, constants.REDIS_SMS_CODE_EXPIRES / 60)
        # 保存到redis中
        pipeline = redis_conn.pipeline()
        pipeline.setex("sms_code_%s" % mobile, constants.REDIS_SMS_CODE_EXPIRES, sms_code)
        pipeline.execute()
        # 返回响应
        return http.JsonResponse({"errmsg": "success", "code": RET.OK})


class ResetPasswordView(View):
    def get(self, request, username):
        mobile = User.objects.filter(username=username).values('mobile')[0]['mobile']
        if not mobile:
            return http.JsonResponse({"status": '404'})
        sms_code = request.GET.get("sms_code")
        redis_conn = get_redis_connection("code")
        redis_sms_code = redis_conn.get("sms_code_%s" % mobile)
        if sms_code != redis_sms_code.decode():
            return http.JsonResponse({"status": '400'})
        data = {
            "user_id": User.objects.filter(username=username).values('id')[0]['id'],
            "access_token": '',
        }
        return http.JsonResponse(data)


class ResetPasswordView2(View):
    def post(self, request, user_id):
        user_dict = json.loads(request.body.decode())
        pwd = user_dict.get("password")
        cpwd = user_dict.get("password2")
        if not all([pwd, cpwd]):
            return http.JsonResponse({"status": '400'})
        if pwd != cpwd:
            return http.JsonResponse({"status": '404'})
        user = User.objects.get(id=user_id)
        if not user:
            return http.JsonResponse({"status": '401'})
        # 数据入库
        user.set_password(pwd)
        user.save()
        return http.JsonResponse({"message": "success", "code": RET.OK})
